package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"travel-mgmt-sys/models"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	price, _ := strconv.Atoi(c.PostForm("price"))
	address := c.PostForm("address")

	travel := models.Travel{
		Title:   title,
		Price:   price,
		Address: address,
	}

	err := models.DB.Create(&travel).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片获取失败",
		})
		return
	}

	if file.Size > 2*1024*1024 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片大小限制2M以内",
		})
		return
	}

	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	}
	url := "http://" + c.Request.Host + "/" + path
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"data": url,
	})
	return

}

func Delete(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Delete(&models.Travel{}, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var travel []models.Travel
	models.DB.Find(&travel)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": travel,
	})
	return
}
